package cn.pangza.redis.utils;

import cn.pangza.redis.exception.ShareLockException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class RedisShareLockUtil {
    @Resource
    private RedisUtil redisUtil;

    private long TIME_OUT = 1000L;

    // 加锁
    public boolean lock(String key, String requestId, long time) {
        // 参数校验
        if(StringUtils.isBlank(key) || StringUtils.isBlank(requestId) || time <= 0) {
            throw new ShareLockException("分布式锁加锁参数异常");
        }
        long currentTime = System.currentTimeMillis();
        long outTime = currentTime + TIME_OUT;
        boolean result = false;
        // 加锁可以有自旋
        while (currentTime < outTime) {
            // 借助 redis setnx 进行锁设置
            result = redisUtil.setNx(key, requestId, time, TimeUnit.MILLISECONDS);

            if(result) return result;

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            currentTime = System.currentTimeMillis();
        }
        return result;
    }

    // 解锁
    public boolean unlock(String key, String requestId) {
        // 参数校验
        if(StringUtils.isBlank(key) || StringUtils.isBlank(requestId)) {
            throw new ShareLockException("分布式锁解锁参数异常");
        }
        try {
            String value = redisUtil.get(key);
            if(requestId.equals(value)) {
                redisUtil.delete(key);
                return true;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }


        return false;
    }

    // 尝试枷锁
    public boolean tryLock(String key, String requestId, long time) {
        // 参数校验
        if(StringUtils.isBlank(key) || StringUtils.isBlank(requestId) || time <= 0) {
            throw new ShareLockException("分布式锁加锁参数异常");
        }
        return redisUtil.setNx(key, requestId, time, TimeUnit.MILLISECONDS);
    }


}
